'use strict'
const path = require('path')
const getArgv = require('./build/getArgv')
const _Config = require('./config/index')
function resolve(dir) {
  return path.join(__dirname, dir)
}

const _publicPathMap = _Config.BASE_URL

// 获取命令行参数
const argv = getArgv()
// IPHOST ip
const _useIpHost = argv.i
const _ip = !_useIpHost || typeof argv.i === 'boolean' ? '172.29.200.239' : argv.i

// 是否关闭 console
const _drop_console = Object.prototype.hasOwnProperty.call(argv, 'dc')
  ? !!argv.dc
  : process.env.NODE_ENV === 'production'

// 获取 _publicPath
function getPublicPath(i = { useIpHost: false, ip: '' }, p = '') {
  // 保底
  let path = _publicPathMap[process.env.NODE_ENV] || '/'
  // 命令行配置（优先级：2）
  if (p) {
    if (_publicPathMap[p]) {
      path = _publicPathMap[p]
    } else {
      if (p !== true) {
        path = p
      }
    }
  }
  // 使用ip（优先级：1）
  if (i.useIpHost) {
    path = path.replace('j1.58cdn.com.cn', i.ip)
  }
  // 开发配置
  if (process.env.NODE_ENV === 'development') {
    path = _publicPathMap['development']
  }
  // 补 /
  if (path.slice(-1) !== '/') {
    path += '/'
  }
  return path
}

// publicPath
const _publicPath = getPublicPath(
  {
    useIpHost: _useIpHost,
    ip: _ip
  },
  argv.p
)

module.exports = {
  publicPath: _publicPath, // 署应用包时的基本 URL。 vue-router hash 模式使用
  outputDir: 'dist', //  生产环境构建文件的目录
  assetsDir: 'static', //  outputDir的静态资源(js、css、img、fonts)目录
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false, // 如果你不需要生产环境的 source map，可以将其设置为 false 以加速生产环境构建。
  devServer: {
    port: 5858, // 端口
    open: true, // 启动后打开浏览器
    overlay: {
      //  当出现编译器错误或警告时，在浏览器中显示全屏覆盖层
      warnings: false,
      errors: true
    },
    proxy: _Config.BASE_PROXY
  },
  configureWebpack: config => {
    config.performance = {
      hints: false
    }
    config.resolve.alias = {
      '@': resolve('src')
    }
    const sassLoader = require.resolve('sass-loader')
    config.module.rules
      .filter(rule => {
        return rule.test.toString().indexOf('scss') !== -1
      })
      .forEach(rule => {
        rule.oneOf.forEach(oneOfRule => {
          const sassLoaderIndex = oneOfRule.use.findIndex(item => item.loader === sassLoader)
          oneOfRule.use.splice(sassLoaderIndex, 0, {
            loader: require.resolve('css-unicode-loader')
          })
        })
      })
  },
  chainWebpack(config) {
    config.plugin('html').tap(args => {
      args[0].title = _Config.BASE_TITLE
      args[0].icon = _Config.BASE_ICON
      return args
    })
    config.plugins.delete('preload')
    config.plugins.delete('prefetch')

    if (process.env.NODE_ENV === 'production') {
      config.output.filename(`static/js/[name].${_Config.BASE_HASH}.js`).end()
      config.output.chunkFilename(`static/js/[name].${_Config.BASE_HASH}.js`).end()
      config.plugin('extract-css').tap(() => [
        {
          filename: `static/css/[name].${_Config.BASE_HASH}.css`
        }
      ])
    }

    const imagesRule = config.module.rule('images')
    imagesRule
      .use('url-loader')
      .loader('url-loader')
      .tap(options => Object.assign(options, { limit: 6144 }))
      .end()

    // set preserveWhitespace
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap(options => {
        options.compilerOptions.preserveWhitespace = true
        return options
      })
      .end()

    // https://webpack.js.org/configuration/devtool/#development
    config.when(process.env.NODE_ENV === 'development', config => config.devtool('cheap-source-map'))

    config.optimization.splitChunks({
      chunks: 'all',
      cacheGroups: {
        libs: {
          name: 'chunk-libs',
          test: /[\\/]node_modules[\\/]/,
          priority: 10,
          chunks: 'initial' // only package third parties that are initially dependent
        },
        elementUI: {
          name: 'chunk-elementUI', // split elementUI into a single package
          priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
          test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
        },
        mdsUI: {
          name: 'chunk-mdsUI', // split mdsUI into a single package
          priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
          test: /[\\/]node_modules[\\/]@bic-fe[\\/]_?mds-ui(.*)/ // in order to adapt to cnpm
        },
        commons: {
          name: 'chunk-commons',
          test: resolve('src/components'), // can customize your rules
          minChunks: 3, //  minimum common number
          priority: 5,
          reuseExistingChunk: true
        }
      }
    })
    config.optimization.runtimeChunk('single')
    // config.optimization.minimize(true)
  }
}
